﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.Patients.ChildWindows;
using MedLink2011.Views.Patients.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.Patients.ViewModels
{
    public class Medical_HistoViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _medical_HistoContext;
        private ObservableCollection<Medical_Histo> _medical_Histo;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.Patient> _patientQuery;
        //
       public Medical_HistoViewModel()
        {
            if (!IsDesignTime)
            {
                _medical_HistoContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadMedical_HistoAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Medical_Histo"
        readonly int loadedPatient_Id = MedLink2011.Views.Patients.ViewModels.PatientViewModel.DashLoad_PK;
        //readonly int loadedPatient_Id = 1;
        private void LoadMedical_HistoAsync()
         {
           if (!_medical_HistoContext.IsSubmitting)
            {
                if (loadedPatient_Id > 0)
                {
                    PerformAsyncQuery<Medical_Histo>(_medical_HistoContext, _medical_HistoContext.GetMedical_HistosForPatientsQuery(loadedPatient_Id), Medical_HistoLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Medical_Histo>(_medical_HistoContext, _medical_HistoContext.GetMedical_HistosQuery(), Medical_HistoLoadedComplete); 
                }
            }
        }

        private EntitySet<Medical_Histo> _medical_HistoCollection;
        public EntitySet<Medical_Histo> Medical_HistoCollection
        {
            get { return _medical_HistoCollection; }
            set
            {
                _medical_HistoCollection = value;
                RaisePropertyChanged("Medical_HistoCollection");
            }
        }

        private Medical_Histo _currentMedical_Histo;
        public Medical_Histo CurrentMedical_Histo
        {
            get { return _currentMedical_Histo; }
            set
            {
                _currentMedical_Histo = value;
                RaisePropertyChanged("CurrentMedical_Histo");
            }
        }

        #endregion "Load Current Medical_Histo"

        #region Commands

        private void EnableCommands()
        {
            AddNewMedical_HistoCommand.IsEnabled = true;
            SaveMedical_HistoCommand.IsEnabled = true;
            DeleteMedical_HistoCommand.IsEnabled = true;
            PrintMedical_HistoCommand.IsEnabled = true;
            SearchMedical_HistoCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewMedical_HistoCommand = new RelayCommand(AddMedical_Histo);
            SaveMedical_HistoCommand = new RelayCommand(SaveMedical_Histo);
            DeleteMedical_HistoCommand = new RelayCommand(DeleteMedical_Histo);
            PrintMedical_HistoCommand = new RelayCommand(PrintMedical_Histo);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchMedical_HistoCommand = new RelayCommand<string>(SearchInMedical_Histo);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentMedical_Histo = (Medical_Histo) _theItem;
            SelectedPatient =
                PatientCollection.Where(c => c.Patient_Id == CurrentMedical_Histo.Patient_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Medical_Histo model = e.DataElement as MedLink2011.Web.Models.Medical_Histo;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Asthma : {0} \r\n"+
			"Adrenal Dysfunction : {1} \r\n"+
			"Arthritis : {2} \r\n"+
			"Blood Clots : {3} \r\n"+
			"Copd : {4} \r\n"+
			"Coronary Artery Disease : {5} \r\n"+
			"Cystic Fibrosis : {6} \r\n"+
			"Diabetes : {7} \r\n"+
			"Diabetes 1 : {8} \r\n"+
			"Diabetes 2 : {9} \r\n"+
			"Endocarditis : {10} \r\n"+
			"Gerd : {11} \r\n"+
			"Gout : {12} \r\n"+
			"Hemolytic Anemia : {13} \r\n"+
			"Hepatic Dysfunction : {14} \r\n"+
			"Hiv Aids : {15} \r\n"+
			"Hypertension : {16} \r\n"+
			"Inflammatory Bowel Disease : {17} \r\n"+
			"Neuromuscular Weakness : {18} \r\n"+
			"Osteoporosis : {19} \r\n",

			model.Asthma,
			model.Adrenal_dysfunction,
			model.Arthritis,
			model.Blood_clots,
			model.COPD,
			model.Coronary_Artery_Disease,
			model.Cystic_Fibrosis,
			model.Diabetes,
			model.Diabetes1,
			model.Diabetes2,
			model.Endocarditis,
			model.GERD,
			model.Gout,
			model.Hemolytic_anemia,
			model.Hepatic_dysfunction,
			model.HIV_AIDS,
			model.Hypertension,
			model.Inflammatory_Bowel_Disease,
			model.Neuromuscular_weakness,
			model.Osteoporosis
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewMedical_HistoCommand
        {
            get;
            private set;
        }
        public RelayCommand SaveMedical_HistoCommand
        {
            get;
            private set;
        }
        public RelayCommand DeleteMedical_HistoCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintMedical_HistoCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchMedical_HistoCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInMedical_Histo( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SaveMedical_Histo()
        {
            CurrentMedical_Histo.Patient_Id = SelectedPatient.Patient_Id;
            CurrentMedical_Histo.write_date = CurrentTime;
            CurrentMedical_Histo.write_uid = CurrentUser;
            _medical_HistoContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Medical_Histo se ha actualizado");
                    RaisePropertyChanged("Medical_HistoCollection");
                    RaisePropertyChanged("CurrentMedical_Histo");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddMedical_Histo()
        {

            MedLink2011.Web.Models.Medical_Histo medical_Histo = new MedLink2011.Web.Models.Medical_Histo();
            Medical_HistosAddCW addNewWindow = new Medical_HistosAddCW();
            addNewWindow.DataContext = medical_Histo;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    medical_Histo.create_date = CurrentTime;
                    medical_Histo.write_date = CurrentTime;
                    medical_Histo.create_uid = CurrentUser;
                    medical_Histo.write_uid = CurrentUser;
                    
                    _medical_HistoContext.Medical_Histos.Add(medical_Histo);
                    _medical_HistoContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Medical_Histo has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadMedical_HistoAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/Patients/Pages/PatientsTitlePage?Medical_History_Id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentMedical_Histo = (Medical_Histo)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<Patient> PatientCollection { get; set; }
        private Patient _selectedPatient;
        public  Patient SelectedPatient
        {
            get { return _selectedPatient; }
            set
            {
                _selectedPatient = value;
                RaisePropertyChanged("SelectedPatient");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //Patient_IdComboBox
            _context = new MedLink2011Context();
            _patientQuery = _context.GetPatientsQuery();
            _patientQuery = _patientQuery.OrderBy(e => e.Patient_Id);
            PerformAsyncQuery<Patient>(_context, _patientQuery, Patient_IdComboBoxLoaded);
            PatientCollection = _context.Patients;
        }
        
        private void Patient_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Patient> e)
        {
            if (!e.HasError)
            {
                SelectedPatient =
                    PatientCollection.Where(c => c.Patient_Id == CurrentMedical_Histo.Patient_Id).SingleOrDefault();
            }
        }


        private void Medical_HistoLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Medical_Histo> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                Medical_HistoCollection = _medical_HistoContext.Medical_Histos;
                CurrentMedical_Histo = Medical_HistoCollection.FirstOrDefault();
                EnableCommands();
            SelectedPatient = PatientCollection.Where(c => c.Patient_Id == CurrentMedical_Histo.Patient_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Medical_Histo> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeleteMedical_Histo()
        {
            _toDelete = true;
            var medical_HistoToDelete = CurrentMedical_Histo;
           if (medical_HistoToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Medical_Histo?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _medical_HistoContext.Medical_Histos.Remove(medical_HistoToDelete);
            _medical_HistoContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta medical_Histo no se puede eliminar ya que existen datos que dependen de esta Medical_Histo.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _medical_HistoContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  medical_Histo ha sido eliminado exitosamente ... ");
                    //LoadMedical_HistoAsync();
                    RaisePropertyChanged("Medical_HistoCollection");
                    CurrentMedical_Histo = Medical_HistoCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintMedical_Histo()
        {
            if (CurrentMedical_Histo != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Medical_Histos_" + CurrentMedical_Histo.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Medical_Histo appt = CurrentMedical_Histo as MedLink2011.Web.Models.Medical_Histo;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new Medical_HistosFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

